
#include <stdint.h>
#include "Contract.h"
#include "IO.h"

#include "i2c_master.h"

#define NUM_X	3
#define NUM_Y	4

static uint8_t keyIsAvailable;

//	static const IO_T keyBacklight = IO_INIT_TABLE(GPIOC, GPIO_PIN_14);

static const IO_T keyCheck = IO_INIT_TABLE(GPIOC, GPIO_PIN_6);


#if 0
void BSP_Keyboard_Backlight_Set(uint8_t state){
	IO_Set(&keyBacklight, !state);
}

static void BSP_Keyboard_BacklightInit(void){
	IO_Init(&keyBacklight, IO_Mode_OUT);
}
#endif 


static void BSP_Keyboard_CheckInit(void){
#if 0
	/* connect EXTI line to key GPIO pin */
	gpio_exti_source_select(GPIO_PORT_SOURCE_GPIOC, GPIO_PIN_SOURCE_6);
	
	/* configure EXTI line */
	exti_init(EXTI_6, EXTI_INTERRUPT, EXTI_TRIG_FALLING);
	exti_interrupt_flag_clear(EXTI_6);
	/* enable and set EXTI interrupt to the lowest priority */
	nvic_irq_enable(EXTI5_9_IRQn, 2U, 0U);
#endif 
}

static int BSP_Keyboard_CheckAvailable(void){
	int i;
	int c = 0;
	int isAvailable;
	
	IO_Init(&keyCheck, IO_Mode_IPD);

	for(i = 0; i < 3; i++){
		if(IO_Get(&keyCheck)){
			c++;
		}
		BSP_Delay_ms(1);
	}
	
	isAvailable = (c > 2);
	
	if(isAvailable){		
		IO_Init(&keyCheck, IO_Mode_IN);
	}
	else{
		IO_Init(&keyCheck, IO_Mode_IPU);
	}
	return isAvailable;
}


void BSP_Keyboard_Init(void){
#if 0
	BSP_Keyboard_BacklightInit();
	BSP_Keyboard_Backlight_Set(0);
#endif 
	IO_Init(&keyCheck, IO_Mode_IN);
	keyIsAvailable = BSP_Keyboard_CheckAvailable();
	if(keyIsAvailable){
		BSP_Keyboard_CheckInit();
		i2c_init();
	}
}

int BSP_Keyboard_IsAvailable(void){
	return keyIsAvailable;
}



#define FTC692A_ADDR	0xAE
#define FTC692A_ADDR_Read	(FTC692A_ADDR | 0x01)

int FTC692A_Read(void){
	if(IO_Get(&keyCheck)){
		return 0;
	}
	uint8_t data[2];
	int ret = i2c_receive(FTC692A_ADDR_Read, data, sizeof(data));
	if(ret){
		return 0;
	}
	return *(uint16_t*)data;
}



static const char keyMap[16] = {
	0x0C, 0x0A, 5, 4, 
	3, 2, 1, (char)-1,
	(char)-1, (char)-1, 0x0B, 0,
	9, 8, 7, 6
};

static int MapToVal(int map){
	int i;
	int val;
	for(i = 0; i < sizeof(keyMap); ++i){
		if(map & (1 << i)){
			val = keyMap[i];
			if(val != (char) -1){
				return val;
			}
		}
	}
	return -1;
}

int BSP_Keyboard_Scan(void){
	int map = FTC692A_Read();
	if(!map){
		return -1;
	}
	
	return MapToVal(map);
}

int BSP_Keyboard_Check(void){
	if(IO_Get(&keyCheck)){
		return 0;
	}
	return 1;
}


void BSP_Keyboard_Lock(uint8_t state){

}



